package cn.edu.xmut.chen.zhlg.zhlg.file.service.impl;

import cn.edu.xmut.chen.zhlg.common.HttpResult.Result;
import cn.edu.xmut.chen.zhlg.common.framework.utils.AssertUtils;
import cn.edu.xmut.chen.zhlg.common.utils.CommonRequestUtils;
import cn.edu.xmut.chen.zhlg.common.utils.ResultType;
import cn.edu.xmut.chen.zhlg.zhlg.file.entity.File;
import cn.edu.xmut.chen.zhlg.zhlg.file.mapper.FileMapper;
import cn.edu.xmut.chen.zhlg.zhlg.file.service.FileService;
import cn.edu.xmut.chen.zhlg.zhlg.user.entity.User;
import cn.edu.xmut.chen.zhlg.zhlg.user.mapper.UserMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.UUID;

@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, File> implements FileService {

    @Value("${upload.directory}")
    private String uploadDirectory;

    @Resource
    private UserMapper userMapper;

    @Override
    public String uploadAvatar(MultipartFile file) {

        // 验证文件是否为空
        if (file == null || file.isEmpty()) {
            AssertUtils.assertTrue(false, ResultType.FAIL,"上传文件为空");
        }

        // 验证文件类型
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
        if (!Arrays.asList("jpg", "jpeg", "png", "gif").contains(fileExtension)) {
            AssertUtils.assertTrue(false,ResultType.FAIL,"上传文件格式有误");
        }

        if (file.getSize() > 10 * 1024 * 1024) {
            AssertUtils.assertTrue(false,ResultType.FAIL,"上传文件超过10MB");
        }

        String filename = "";
        try {
            // 生成存储路径和文件名
            String newFilename = UUID.randomUUID()+ "." + fileExtension;
            filename = newFilename;
            Path uploadPath = Paths.get(uploadDirectory);

            // 确保目录存在
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 保存文件
            Path targetPath = uploadPath.resolve(newFilename);
            file.transferTo(targetPath.toFile());

            // 更新用户头像信息
            User user = userMapper.selectById(CommonRequestUtils.getLoginId());
            if (user == null) {
                AssertUtils.assertTrue(false,ResultType.FAIL,"用户不存在");
            }

            // 生成访问URL (可根据实际需求调整)
            String fileUrl = "/static/avator/" + newFilename;

            user.setPic(fileUrl);
            userMapper.updateById(user);

        } catch (IOException e) {
            log.error("头像上传失败", e);
            AssertUtils.assertTrue(false,ResultType.FAIL,"头像上传失败");
        } catch (Exception e) {
            log.error("头像上传处理异常", e);
            AssertUtils.assertTrue(false,ResultType.FAIL,"头像上传处理异常");
        }

        return filename;
    }
}
